package cn.dida.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.dida.exception.BizzException;
import cn.dida.model.HttpResponseBodyWrapper;
import cn.dida.model.Pageable;
import cn.dida.model.Staff;
import cn.dida.model.UserSession;
import cn.dida.service.StaffService;
import cn.dida.util.DateUtils;
import cn.dida.util.ExcelUtil;

/**
 * <p>系统管理-->账户管理</p>
 * @author weiwei
 * 
 * */
@Controller
public class StaffController extends BaseController {
    @Autowired
    private StaffService staffService;

    /**
     * 账户列表
     * @param request
     * @param keyword 查询条件
     * @param state 状态，1：正常、2：禁用
     * @param page 分页游标
     * @return ModelAndView 账户列表页面
     * @throws Exception
     */
    @GetMapping("/staff")
    public ModelAndView staff(HttpServletRequest request, String keyword, Integer state, Integer page) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);

        page = (page == null || page < 1) ? 1 : page;
        keyword = StringUtils.trimToNull(keyword);

        Pageable<Staff> staffList = staffService.queryStaff(userSession.getCompanyId(), keyword, state, page);
        model.put("staffList", staffList);
        model.put("keyword", keyword);
        model.put("state", state);
        model.put("account",userSession.getAccount());
        model.put("admin",userSession.getAdmin());
        return new ModelAndView("staff_list").addAllObjects(model);
    }
    /**
     * 账户管理数据导出
     * @param request
     * @param response
     * @param keyword 查询条件 
     * @param state 状态，1：正常、2：禁用
     * @return
     * @throws Exception
     */
    @GetMapping("/staff/export")
    public ModelAndView branch_export(HttpServletRequest request, HttpServletResponse response, String keyword, Integer state) throws Exception {
    	UserSession userSession = getUserSession(request);
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	
    	if(StringUtils.isNotBlank(keyword)){//网点名称
    		paramMap.put("keyword", keyword);
    	}
    	if(state != null){
    		paramMap.put("state", state);
    	}
    	
		List<Staff> exportList = staffService.queryStaffForExport(userSession.getCompanyId(), keyword, state);
		
    	String fileName="账户管理数据导出"+DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");
    	
    	List<Map<String,Object>> list= new ArrayList<Map<String,Object>>(exportList.size());
    	
    	Map<String,Object> fmap = null;
    	for(Staff obj : exportList){
    		fmap=new HashMap<String, Object>();
    		Long tid = NumberUtils.toLong(obj.getId().toString(), 0L);
    		fmap.put("id", tid);
    		fmap.put("account", obj.getAccount());
    		fmap.put("mobile", obj.getMobile());
    		if(obj.getState() == 1){
    			fmap.put("state", "正常");
    		}else if(obj.getState() == 2){
    			fmap.put("state", "停用");
    		}
    		
    		list.add(fmap);
    	}
    	
    	String columnNames[] = {"ID","账户名称","手机号","状态"};//列名
    	String keys[] = {"id","account","mobile","state"};//map中的key
    	ByteArrayOutputStream os = new ByteArrayOutputStream();
    	try {
    		ExcelUtil.createWorkBook(list,keys,columnNames).write(os);
    	} catch (IOException e) {
    		e.printStackTrace();
    	}
    	byte[] content = os.toByteArray();
    	InputStream is = new ByteArrayInputStream(content);
    	// 设置response参数，可以打开下载页面
    	response.reset();
    	response.setContentType("application/vnd.ms-excel;charset=utf-8");
    	response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
    	ServletOutputStream out = response.getOutputStream();
    	BufferedInputStream bis = null;
    	BufferedOutputStream bos = null;
    	try {
    		bis = new BufferedInputStream(is);
    		bos = new BufferedOutputStream(out);
    		byte[] buff = new byte[2048];
    		int bytesRead;
    		// Simple read/write loop.
    		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
    			bos.write(buff, 0, bytesRead);
    			bos.flush();
    		}
    	} catch (final IOException e) {
    		throw e;
    	} finally {
    		if (bis != null)
    			bis.close();
    		if (bos != null)
    			bos.close();
    	}
    	
    	return null;
    }

    /**
     * 新增账户
     * @param request
     * @param staff 账户实体信息
     * @return HttpResponseBodyWrapper 封装操作标记（ true新增成功，false新增失败）
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/staff")
    public HttpResponseBodyWrapper postStaff(HttpServletRequest request, @RequestBody Staff staff) throws Exception {
       // Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);

        staff.setCompanyId(userSession.getCompanyId());
        staff.setAccount(StringUtils.trimToNull(staff.getAccount()));
        staff.setMobile(StringUtils.trimToNull(staff.getMobile()));
        staff.setPwd(StringUtils.trimToNull(staff.getPwd()));
        staff.setAdmin(false);

        if (staff.getAccount() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入账号");
        }
        if (staff.getMobile() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入手机号");
        }
        if (staff.getPwd() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入密码");
        }
        if (!Pattern.matches("\\d{11}", staff.getMobile())) {
            throw new BizzException(BizzException.error_code_invalid_params, "手机号输入有误");
        }

        Boolean result = staffService.insertStaff(staff);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 获取账户信息
     * @param request
     * @param id 账户id
     * @return HttpResponseBodyWrapper 封装单个账户实体数据
     * @throws Exception
     */
    @ResponseBody
    @GetMapping("/staff/{id}")
    public HttpResponseBodyWrapper getStaff(HttpServletRequest request, @PathVariable Integer id) throws Exception {
       // Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        Staff result = staffService.getStaff(userSession.getCompanyId(), id);
        result.setPwd("");
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 更新账户
     * @param request
     * @param staff 账户实体信息
     * @return HttpResponseBodyWrapper 封装操作标记（ true更新成功，false更新失败）
     * @throws Exception
     */
    @ResponseBody
    @PutMapping("/staff/{id}")
    public HttpResponseBodyWrapper putStaff(HttpServletRequest request, @RequestBody Staff staff) throws Exception {
        //Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);

        staff.setCompanyId(userSession.getCompanyId());
        staff.setAccount(StringUtils.trimToNull(staff.getAccount()));
        staff.setMobile(StringUtils.trimToNull(staff.getMobile()));
        staff.setPwd(StringUtils.trimToNull(staff.getPwd()));

        if (staff.getAccount() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入账号");
        }
        if (staff.getMobile() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入手机号");
        }
        /*if (staff.getPwd() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入密码");
        }*/
        if (!Pattern.matches("\\d{11}", staff.getMobile())) {
            throw new BizzException(BizzException.error_code_invalid_params, "手机号输入有误");
        }


        Boolean result = staffService.updateStaff(staff);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 删除账户
     * @param request
     * @param id 账户id
     * @return HttpResponseBodyWrapper 封装操作标记（ true删除成功，false删除失败）
     * @throws Exception
     */
    @ResponseBody
    @DeleteMapping("/staff/{id}")
    public HttpResponseBodyWrapper deleteStaff(HttpServletRequest request, @PathVariable Integer id) throws Exception {
        //Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        Boolean result = staffService.deleteStaff(userSession.getCompanyId(), id);
        return new HttpResponseBodyWrapper(result);
    }
    
    /**
     * 重置密码
     * @param request
     * @param staffId 帐户id
     * @param companyId 公司id
     * @return HttpResponseBodyWrapper 包装操作标识，true表示重置成功，false表示重置失败
     * @throws Exception
     */
    @ResponseBody
    @GetMapping("/staff/resetPwd/{staffId}/{companyId}")
    public HttpResponseBodyWrapper resetPassword(HttpServletRequest request, @PathVariable Integer staffId,@PathVariable Integer companyId) throws Exception {
        //UserSession userSession = getUserSession(request);
        boolean result = staffService.resetPassword(companyId, staffId) == 1;
        return new HttpResponseBodyWrapper(result);
    }
    /**
     * 跳转到修改密码页面
     * @param request
     * @param newPassword 
     * @return  ModelAndView 修改密码页面
     * @throws Exception
     */
    @GetMapping("/staff/editPwd")
    public ModelAndView editPwdPage(HttpServletRequest request) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        //UserSession userSession = getUserSession(request);
        //model.put("oldPassword", userSession.get)
        return new ModelAndView("staff_editPwd").addAllObjects(model);
    }
    /**
     * 校验原密码
     * @param request
     * @param oldPassword 原密码
     * @return HttpResponseBodyWrapper 包装操作标识，true表示原密码输入正确，false表示原密码输入不正确
     * @throws Exception
     */
    @ResponseBody
    @GetMapping("/staff/checkOldPwd/{oldPassword}")
    public HttpResponseBodyWrapper checkOldPwd(HttpServletRequest request, @PathVariable String oldPassword) throws Exception {
        UserSession userSession = getUserSession(request);
        if(oldPassword == null){
        	throw new BizzException(BizzException.error_code_invalid_params, "请输入原密码");
        }
        boolean result = staffService.checkOldPassword(userSession.getCompanyId(), userSession.getId(), oldPassword) == 1;
        return new HttpResponseBodyWrapper(result);
    }
    /**
     * 修改密码
     * @param request
     * @param newPassword 新密码
     * @return HttpResponseBodyWrapper 包装操作标识，true表示修改成功，false表示修改失败
     * @throws Exception
     */
    @ResponseBody
    @GetMapping("/staff/saveNewPassword/{newPassword}")
    public HttpResponseBodyWrapper editPwd(HttpServletRequest request, @PathVariable String newPassword) throws Exception {
        UserSession userSession = getUserSession(request);
        boolean result = staffService.editPassword(userSession.getCompanyId(), userSession.getId(), newPassword) == 1;
        return new HttpResponseBodyWrapper(result);
    }
}
